package com.rytong.tools.ui;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.RadioButton;
import com.rytong.tools.ui.Component;
import com.rytong.tools.utils.Utils;

@SuppressWarnings("deprecation")
public class LPSegment extends Component {

    /**
     * 此segment在此组的位置,从0开始
     */
    int groupNum_;

    /**
     * 此组segment的个数
     */
    int groupCount_;

    /**
     * 存放本组segment元素
     */
    ArrayList<LPSegment> segmentList_ = new ArrayList<LPSegment>(2);

    // 未选中时字体颜色
    final int UN_SEGMENTRADIO = 0xFF5E5F5E;
    // 选中时字体颜色
    final int SEGMENTRADIO = 0xFFFFFFFF;
    
    public class MyLPSegment extends RadioButton implements CompositedComponent {

        public MyLPSegment(Context context, String nodeValue) {
            super(context);
            setText(nodeValue);
        }

        @Override
        public Component composited() {
            return LPSegment.this;
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            int touchEvent = event.getAction();
            boolean isAction = false;
            switch (touchEvent) {
            case MotionEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
                isAction = true;
                break;
            case MotionEvent.ACTION_UP:
            	// 抬起tr恢复颜色。
            	trUpColor(tr_, llvSV_);
                // 设置选中项
                setCheckedManually();
                // 设置segment的lua点击事件
                isAction = onClick((String) composited().property_.get("onclick"));
                break;
            default:
                isAction = super.onTouchEvent(event);
            }
            return isAction;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            Paint paint = getPaint();
            //***画笔默认黑色字体
            if (this.isChecked()) {
                canvas.drawBitmap(focusImg_, 0, 0, paint);
//                paint.setColor(SEGMENTRADIO);
            } else {
                canvas.drawBitmap(unFocusImg_, 0, 0, paint);
//                paint.setColor(UN_SEGMENTRADIO);
            }
           // 给segment之间添加分割线。
            paint.setColor(Color.GRAY); // 线条颜色。
            paint.setStrokeWidth(2); // 线条粗细。
            if(groupNum_ == 0){ // 第一个元素，画在右侧。
                canvas.drawLine(width_, 0, width_, height_, paint);
            } else if(groupNum_ + 1 == groupCount_){ // 最后一个元素。
                // 不画。
            } else { // 中间的元素，也画在右侧。
                canvas.drawLine(width_, 0, width_, height_, paint);
            }

            String content = "";
            // 绘制节点值, 未设置text值时取value
            if (property_.get("text") != null && !property_.get("text").equals("")) {
                content = property_.get("text").toString();
            } else {
                content = property_.get("value");
            }
            if (content != null) {
                int xText = ((getWidth() - (int) paint.measureText(content)) >> 1);
                int yText = ((getHeight() + (int) paint.getTextSize()) >> 1) - 2;
                if(this.isChecked()){
                	paint.setColor(SEGMENTRADIO);
                } else {
                	paint.setColor(UN_SEGMENTRADIO);
                }
                canvas.drawText(content, xText, yText, paint);
            }
        }

    }

    @Override
    public void initRealView(Activity activity, String nodevalue) {
        realView_ = new MyLPSegment(activity, nodevalue);
    }

    @Override
    public String getPropertyByName(String key) {
    	// value \ text 均取选中控件的值
    	if (segmentList_ != null && key != null && (key.equals("value") || key.equals("text"))) {
    	    String thisName = (String) getPropertyByName("name");
    	    String tempName;
    	    LPSegment tempSegment = null;
    	    for (int i = 0; i < segmentList_.size(); i++) {
    	        tempSegment = segmentList_.get(i);
    	        tempName = (String) tempSegment.getPropertyByName("name");
    	        
    	        if (tempName != null && tempName.equals(thisName) && tempSegment.isChecked()) {                    
    	        	break;
                } else {
                    tempSegment = null;
                }
            }
            if (tempSegment != null) {
                String value = tempSegment.property_.get(key);
                return value == null ? "" : value;
            } else {
                return "";
            }
        } else {
            return super.getPropertyByName(key);
        }
    }

    /**
     * @return
     */
    public boolean isChecked() {
    	if(realView_ != null){
    		MyLPSegment seg = (MyLPSegment) realView_;
    		return seg.isChecked();
    	} 
    	return false;
    }

    @Override
    public void mouldH() throws Exception {
        MyLPSegment segmentView = null;
        if (null != realView_)
            segmentView = (MyLPSegment) realView_;
        else
            return;

        // 设置画笔抗锯齿
        getPaint().setAntiAlias(true);
        if (cssStyle_ != null) {
            // 设置字体大小
            String temp = cssStyle_.getProperty(CssStyle.FONTSIZE);
            if (null != temp && !temp.equals("")) {
                int fontSize = Integer.parseInt(fixedPX(temp));
                fontSize = Utils.getFontSize(fontSize);
                if (fontSize > 0) {
                	// 设置画笔大小
                	getPaint().setTextSize(fontSize);
                }
            }
            // 设置字体颜色
            temp = null;
            temp = cssStyle_.getProperty(CssStyle.COLOR);
            if (null != temp && !temp.equals("")) {
                int cs_fontColor = Utils.getColorValue(temp);
                // 设置画笔颜色
                getPaint().setColor(cs_fontColor);
            }
        }

        ViewParent parent = segmentView.getParent();
        if (parent instanceof LPSegmentLayout.MyLPSegmentLayout) {
            return;
        }
        if (parentComponent_ != null) {
            parentComponent_.removeView(this);
            String segmentLayoutName = null;
            String childName = null;
            if (this instanceof LPSegment) {
                if (parentComponent_.segmentLayout_ == null) {
                    addSegmentLayoutToParent();

                } else {
                    childName = getPropertyByName("name");
                    segmentLayoutName = parentComponent_.segmentLayout_.getPropertyByName("name");
                    if (segmentLayoutName != null && childName != null && segmentLayoutName.equals(childName)) {
                        parentComponent_.segmentLayout_.segmentList_.add(this);
                        parentComponent_.segmentLayout_.addView(this);
                        parentComponent_.segmentLayout_.mouldH();
                    } else if (segmentLayoutName != null && childName != null && !segmentLayoutName.equals(childName)) {
                        addSegmentLayoutToParent();
                    }
                }

            }
        }
        
        // 设置选中项
        String checked = getPropertyByName("checked");
        if(checked.equals("checked")){
            this.setChecked(true);
        } else {
            this.setChecked(false);
        }
    }

    private void setChecked(boolean b) {
        // TODO Auto-generated method stub
        if (null != realView_) {
            MyLPSegment temp = (MyLPSegment) realView_;
            temp.setChecked(b);
        }
    }

    /**
     * @throws Exception
     *             将switchlayout添加到父布局中
     */
    private void addSegmentLayoutToParent() throws Exception {
        parentComponent_.segmentLayout_ = new LPSegmentLayout();
        parentComponent_.segmentLayout_.initRealView(getActivity(), "");
        parentComponent_.segmentLayout_.setTag("segmentLayout_");
        parentComponent_.segmentLayout_.isAfterBr_ = isAfterBr_;
        parentComponent_.segmentLayout_.attributes_ = attributes_;
        parentComponent_.segmentLayout_.property_ = property_;
        parentComponent_.segmentLayout_.setCssStyle(cssStyle());
        parentComponent_.segmentLayout_.addView(this);
        parentComponent_.segmentLayout_.segmentList_.add(this);

        
        parentComponent_.addView(parentComponent_.segmentLayout_);
        parentComponent_.segmentLayout_.mouldW();
        parentComponent_.segmentLayout_.mouldH();
        parentComponent_.segmentLayout_.adjustXY();
        Component.VWIDGETARRAY.add(parentComponent_.segmentLayout_);
    }

    public void adjustXY() {

    }

    public void setCheckedManually() {
        LPSegment seg = null;
        for (int i = 0; i < segmentList_.size(); i++) {
            seg = segmentList_.get(i);
            if (seg == this) {
                seg.setChecked(true);
            } else {
                seg.setChecked(false);
            }
        }
    }

    public void setSegmentIcon() {
//        Bitmap segmentAllImg = null;
//        segmentAllImg = Utils.getBitmapFromResources(getActivity(), "segment_radio_all");
//        if (null != segmentAllImg) {
//            focusImg_ = Bitmap.createBitmap(segmentAllImg, 0, 0, segmentAllImg.getWidth() >> 1,
//                    segmentAllImg.getHeight());
//            unFocusImg_ = Bitmap.createBitmap(segmentAllImg, (segmentAllImg.getWidth() >> 1) + 1, 0,
//                    (segmentAllImg.getWidth() >> 1) - 1, segmentAllImg.getHeight());
//        }
//        if (!segmentAllImg.isRecycled()) {
//            segmentAllImg.recycle();
//        }
//        segmentAllImg = null;
    	// add by cheng.l 2013.06.22
        if(groupNum_ == 0){//创建最左边segment的图片
        	focusImg_ = Utils.getBitmapFromResources(getActivity(), "segment_focus_left");   	
        	unFocusImg_ = Utils.getBitmapFromResources(getActivity(), "segment_unfocus_left");
        }else if(groupNum_ == groupCount_-1){//创建最右边segment的图片
        	focusImg_ = Utils.getBitmapFromResources(getActivity(), "segment_focus_right");   	
        	unFocusImg_ = Utils.getBitmapFromResources(getActivity(), "segment_unfocus_right");
        }else{//创建最中间segment的图片
        	Bitmap middle1 = Utils.getBitmapFromResources(getActivity(), "segment_focus_left");   	
        	Bitmap middle2 = Utils.getBitmapFromResources(getActivity(), "segment_unfocus_left");
        	focusImg_ = Bitmap.createBitmap(focusImg_, 20, 0, 20, focusImg_.getHeight());
        	unFocusImg_ = Bitmap.createBitmap(unFocusImg_, 20, 0, 20, unFocusImg_.getHeight());
        	if(!middle1.isRecycled()){
        		middle1.recycle();
        	}
         	if(!middle2.isRecycled()){
         		middle2.recycle();
        	}
         	middle1 = null;
         	middle2 = null;
        }
        try {
            if (width_ <= 0) {
                width_ = getAcquiescentWidth();
                if (width_ <= 0)
                    width_ = focusImg_.getWidth();
            }
            if (height_ <= 0) {
                height_ = getAcquiescentHeight();
                if (height_ <= 0)
                    height_ = focusImg_.getHeight();
            }
            //focusImg_ = makeSegmentRadio(focusImg_, width_);
            focusImg_ = Bitmap.createScaledBitmap(focusImg_, width_, height_, true);
            //unFocusImg_ = makeSegmentRadio(unFocusImg_, width_);
            unFocusImg_ = Bitmap.createScaledBitmap(unFocusImg_, width_, height_, true);
        } catch (Exception e) {
            Utils.printOutToConsole(e.getMessage());
        }
    }

    Bitmap makeSegmentRadio(Bitmap imgOri, int width) throws Exception {
        int ori_w = imgOri.getWidth();
        int ori_h = imgOri.getHeight();
        int[] ori_rgb = new int[ori_w * ori_h];
        int[] dst_rgb = new int[width * ori_h];

        int dst = 0;
        int src = 0;
        imgOri.getPixels(ori_rgb, 0, ori_w, 0, 0, ori_w, ori_h);

        int middle = width - ori_w;
        // Copy the first 6 columns from the ori image to the left border.
        for (int i = 0; i < ori_h; ++i) {
            if (i > 0) {
                src = i * ori_w;
            }

            if (groupNum_ == 0) {
                // 绘制带有segment属性组的第一个控件
                for (int j = 0; j < ori_w; ++j) {
                    dst_rgb[dst++] = ori_rgb[src++];
                }
                src -= 1;
                // Copy background from the 6-th column of the source image.
                for (int j = ori_w; j < width; ++j) {
                    dst_rgb[dst++] = ori_rgb[src];
                }
            } else if (groupNum_ + 1 == groupCount_) {
                // 绘制带有segment属性组的最后一个控件

                for (int j = 0; j < ori_w; ++j) {
                    src++;
                }
                src -= 1;
                // Copy background from the 6-th column of the source image.
                for (int j = 0; j < middle; ++j) {
                    dst_rgb[dst++] = ori_rgb[src];
                }
                // Copy the reverse of ori image to the right border.
                for (int j = middle; j < width; ++j) {
                    dst_rgb[dst++] = ori_rgb[src--];
                }
            } else {
                for (int j = 0; j < ori_w; ++j) {
                    src++;
                }
                src -= 1;
                for (int j = 0; j < width; ++j) {
                    dst_rgb[dst++] = ori_rgb[src];
                }
            }
        }
        Bitmap imgDst = null;
        imgDst = Bitmap.createBitmap(dst_rgb, width, ori_h, Bitmap.Config.ARGB_8888);
        return imgDst;
    }
    
    /**
     * name , value , text 目前只针对这三个属性有效
     * */
    public void setPropertyByNameToCheckedItem(String key , String value){
        
        if (segmentList_ != null && key != null && !key.equals("")) {
            
            String thisname = (String) getPropertyByName("name");
            String tempName;
            LPSegment tempSegment = null;
            for (int i = 0; i < segmentList_.size(); i++) {
                tempSegment = segmentList_.get(i);
                tempName = (String) tempSegment.getPropertyByName("name");
                
                if (tempName != null && tempName.equals(thisname) && tempSegment.isChecked()) {
                    tempSegment.property_.put(key, value);
                    break;
                } 
            }
        }
    }
    
    @Override
    public void releaseResource(Component component) {
    	super.releaseResource(component);
    	if(segmentList_ != null){
    		segmentList_.clear();
    		segmentList_ = null;
    	}
    }
}
